package com.toune.movie.mvp.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.nightonke.boommenu.BoomButtons.BoomButton;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.OnBoomListener;
import com.toune.movie.R;
import com.toune.movie.base.AppConstant;
import com.toune.movie.base.BaseFragment;
import com.toune.movie.base.myUtil.MyUtil;
import com.toune.movie.base.myview.BuilderManager;
import com.toune.movie.base.myview.RxPopupSingleView;
import com.toune.movie.mvp.activity.ComicVideoActivity;
import com.toune.movie.mvp.activity.MainActivity;
import com.toune.movie.mvp.activity.MovieVideoActivity;
import com.toune.movie.mvp.activity.SearchActivity;
import com.toune.movie.mvp.activity.TvVideoActivity;
import com.toune.movie.mvp.activity.VarietyVideoActivity;
import com.toune.movie.mvp.adapter.AdapterMovieContent;
import com.toune.movie.mvp.contract.MovieContract;
import com.toune.movie.mvp.presenter.MoviePresenter;
import com.toune.movie.vo.MovieContentVo;
import com.vondear.rxtool.RxClipboardTool;
import com.vondear.rxtool.RxDeviceTool;
import com.vondear.rxtool.RxKeyboardTool;
import com.vondear.rxtool.model.ActionItem;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2018/5/9.
 */

public class MovieFragment extends BaseFragment<MoviePresenter> implements MovieContract.View {

    private static MovieFragment fragment;
    @BindView(R.id.search_et)
    EditText searchEt;
    @BindView(R.id.search_btn)
    Button searchBtn;

    @BindView(R.id.bmb2)
    BoomMenuButton bmb2;
    @BindView(R.id.personal_iv)
    ImageView personalIv;
    @BindView(R.id.mLreclView)
    RecyclerView mLreclView;
    Unbinder unbinder;
    private RxPopupSingleView titlePopup;

    public static MovieFragment newInstance() {
        if (fragment == null) {
            fragment = new MovieFragment();
        }
        return fragment;
    }

    @Override // 实例化presenter
    public MoviePresenter initPresenter() {
        return new MoviePresenter();
    }

    @Override
    public void loadMore() {

    }

    @Override
    public void refreData() {
        mPresenter.getDatas();
    }

    @Override
    protected void initData() {
        if (AVUser.getCurrentUser() != null && AVUser.getCurrentUser().getAVFile("image") != null) {
            Glide.with(getContext()).load(AVUser.getCurrentUser().getAVFile("image").getUrl()).apply(new RequestOptions().circleCrop()).into(personalIv);
        }
        for (int i = 0; i < 4; i++) {
            bmb2.addBuilder(BuilderManager.getSquareTextOutsideCircleButtonBuilder());
        }
        bmb2.setOnBoomListener(new OnBoomListener() {
            @Override
            public void onClicked(int index, BoomButton boomButton) {
                Intent intent = new Intent();
                switch (index) {
                    case 0:
                        intent.setClass(getContext(), MovieVideoActivity.class);
                        intent.putExtra("url", "http://www.52xsba.com/movie.php?m=list.php?cat=all&pageno=1");
                        startActivity(intent);
                        break;
                    case 1:
                        intent.setClass(getContext(), TvVideoActivity.class);
                        intent.putExtra("url", "http://www.52xsba.com/tv.php?m=list.php?cat=all&pageno=1");
                        startActivity(intent);
                        break;
                    case 2:
                        intent.setClass(getContext(), VarietyVideoActivity.class);
                        intent.putExtra("url", "http://www.52xsba.com/zongyi.php?m=list.php?cat=all&pageno=1");
                        startActivity(intent);
                        break;
                    case 3:
                        intent.setClass(getContext(), ComicVideoActivity.class);
                        intent.putExtra("url", "http://www.52xsba.com/dongman.php?m=list.php?cat=all&pageno=1");
                        startActivity(intent);
                        break;
                }
            }

            @Override
            public void onBackgroundClick() {

            }

            @Override
            public void onBoomWillHide() {

            }

            @Override
            public void onBoomDidHide() {

            }

            @Override
            public void onBoomWillShow() {

            }

            @Override
            public void onBoomDidShow() {

            }
        });
    }

    List<AVObject> searchList = new ArrayList<>();

    @Override
    public void init(Bundle savedInstanceState) {
        MyUtil.showProDialog(getContext());
        mPresenter.getDatas();
//        AVQuery<AVObject> avQuery = new AVQuery<>(AppConstant.TAB_SEARCH);
//        if (AVUser.getCurrentUser() != null) {
//            avQuery.whereMatches("userId", AVUser.getCurrentUser().getObjectId());
//        } else {
//            avQuery.whereMatches("phoneId", RxDeviceTool.getUniqueSerialNumber());
//        }
//        avQuery.orderByDescending("updatedAt");
//        avQuery.limit(5);
//        avQuery.findInBackground(new FindCallback<AVObject>() {
//            @Override
//            public void done(List<AVObject> list, AVException e) {
//                if (e == null) {
//                    searchList = list;
//                }
//            }
//        });
    }

    private void initPopupView(final List<AVObject> avObjects) {
        titlePopup = new RxPopupSingleView(getContext(), ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, R.layout.popupwindow_search_layout);
        for (int i = 0; i < avObjects.size(); i++) {
            titlePopup.addAction(new ActionItem(avObjects.get(i).getString("context")));
        }
        titlePopup.setItemOnClickListener(new RxPopupSingleView.OnItemOnClickListener() {

            @Override
            public void onItemClick(ActionItem item, int position) {
                // TODO Auto-generated method stub
                searchEt.setText(avObjects.get(position).getString("context"));
                search(avObjects.get(position).getString("context"));
            }
        });
        if (searchList.size() > 0) {
            titlePopup.show(searchEt);
        }
    }

    private void search(String context) {
        AVQuery<AVObject> avQuery = new AVQuery<>(AppConstant.TAB_SEARCH);
        avQuery.whereMatches("context", context);
        avQuery.findInBackground(new FindCallback<AVObject>() {
            @Override
            public void done(List<AVObject> list, AVException e) {
                if (e == null) {
                    if (list.size() == 0) {
                        insertDb();
                    }
                } else {
                    insertDb();
                }
            }
        });
        insertDb();
        Intent intent = new Intent(getContext(), SearchActivity.class);
        intent.putExtra("searchText", context);
        startActivity(intent);
    }

    private void insertDb() {
        //搜素历史存进数据库
        AVObject avObject = new AVObject(AppConstant.TAB_SEARCH);
        if (AVUser.getCurrentUser() != null) {
            avObject.put("userId", AVUser.getCurrentUser().getObjectId());
        }
        avObject.put("phoneId", RxDeviceTool.getUniqueSerialNumber());
        avObject.put("context", searchEt.getText().toString());
//        avObject.addUnique("context", searchEt.getText().toString());
        avObject.saveInBackground();
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_movie;
    }

    @Override
    public void showError(String msg) {

    }

    @Override
    public void useNightMode(boolean isNight) {

    }

    @Override
    public void setDatas(final List<MovieContentVo> movieContentVos) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                notifyAllAdapter(movieContentVos);
            }
        });
    }

    private void notifyAllAdapter(List<MovieContentVo> movieContentVos) {
        AdapterMovieContent adapterMovieContent = new AdapterMovieContent(R.layout.adapter_movie_content, movieContentVos);
        mLreclView.setLayoutManager(new LinearLayoutManager(getContext()));
        mLreclView.setAdapter(adapterMovieContent);
        MyUtil.hidProDialog();
    }

    @OnClick({R.id.search_btn, R.id.personal_iv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_btn:
                search(searchEt.getText().toString());
                break;
            case R.id.personal_iv:
                MainActivity.mainActivity.showMenu();
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
